import store from '../store'
// import { filterMemberName } from '@/utils/filterName'
import bus from '@/plugins/bus'

import {getGroupInfo} from '@/api/group'
import {getUserInfo} from '@/api/userInfo'
import { deleteChatSession } from '@/api/session'

import utils from "IM/utils/utils";

let time = null
// 不需要往消息列表插入的, 这个信息本来会话中就有，收到回执改变unread 属性
export async function msgCallback(message, newMsg, replyIndex) {
  let reply = newMsg;
  let replyList = store.getters.replyList;
  
  // 消息已读回执, 将消息设置为已读， replyList 的每一个会话对象下方挂载 msgList 这个消息数组
  // message 本身是条新信息，所有就是sender 对于我的会话列表中的聊天对象（因为这个100 的ws 消息是对方发出来的啊，也就是我列表中那个的对象）
  if (message.action == '100') {
     let  reply = replyList.find(item=>item.sourceId == message.sender);  // 找到会话
      reply?.msgList?.forEach((msg) => {  
        if (String(message.content) == String(msg.id)) {  // 找到这个信息
          msg.unread = false; // 设置为已读
        }
      })
      store.commit('setReplyList', replyList)
    return
  }


   // 单聊撤回消息 ---- 更改本地的信息存储
   if (message.action == '101') {
   
    let name =  message.sender == reply.sourceId ? reply.name :'你';
    let tips = name + '撤回了一条消息';
    if(reply){
      reply.msgList.forEach((msg, msgIndex) => {
        if (msg.id == message.content) {
          reply.msgList[msgIndex].withdraw = true
          reply.msgList[msgIndex].reEdit = true;
        }
      })
      reply.messageId = message.id;
      reply.message = tips;

     // 自身放到msgList 中去
     message = Object.assign(message, {
      msg: name + "撤回了一条消息",
      tips: name + "撤回了一条消息",
      deleted: 1  // 自己本身不显示
    })
    reply.msgList.push(message)

    replyList =  utils.calcReplyListSort(replyList, reply);
    store.dispatch('setReplyList', {replyList:replyList, chatList:reply.msgList})


    }
 
    
   
    return
  }

  if (message.action === '102') {
    // 好友改头像
      bus.$emit("usRefresh", message.sender);  
    return
  }

  // 群聊 撤回
  if (message.action == '310') {
    // 单聊撤回消息
    let resGroupInfo  = await getGroupInfo(message.sender)  // 这里sender 是groupId
    let data  = resGroupInfo.data.data;
    if (!data) return;
    const memberInfo = data.memberList.find(item=>item.uid == message.extra);
    let name = store.state.user.id == memberInfo.uid ? '你' : memberInfo.name; // 判断是不是自己
    if (!reply) {
      reply = {
        id: data.id, 
        sourceId: data.id,  
        action: '3',
        title: '',
        name: data.name,
        msgList: [],
        groups: [],
        type:'group',
        motto: data.motto,
        newmsgcount:0,
        badge: 0,
        memberList: data.memberList,
        uid: data.uid,
        state: data.state,
        refer:{ 
          id :message.sender,
          sourceId: message.sender,  
          name: data.name,
          avatar:"", 
          action: message.action 
        },
      }
    }
    
    // 找到改掉 --- 找到原始信息改掉
    reply.msgList.forEach((msg, msgIndex) => {
      if (msg.id == message.content) {
        reply.msgList[msgIndex].withdraw = true
        reply.msgList[msgIndex].reEdit = true;
      }
    });

    reply.messageId = message.id;
    reply.message = name + "撤回了一条消息";
    // 自身放到msgList 中去
    message = Object.assign(message, {
      msg: name + "撤回了一条消息",
      tips: name + "撤回了一条消息",
      deleted: 1
    })
    reply.msgList.push(message)


    replyList =  utils.calcReplyListSort(replyList, reply);
    store.dispatch('setReplyList', {replyList:replyList, chatList:reply.msgList})
    
    return
  }


  //  对方键盘正在输入， 108 键盘输入回执
  time && clearTimeout(time)
  if (message.action === '108') {
    // 正在输入状态
    if(message.sender !== store.state.currentChatId) return;
    store.commit('setEntering', true)
    time = setTimeout(() => {
      store.commit('setEntering', false)
      time = null
    }, 3000)
    return
  }
 
 

  if (message.action === '105') {
    // console.log("在线好友请求");
    // 添加好友请求
    const path = window.location.pathname
    const applyFriend = {
      action: message.action,
      content: message.content,
      extra: message.extra,
      format: message.format,
      id: message.id,
      receiver: message.receiver,
      sender: message.sender,
      timestamp: message.timestamp,
      title: message.title,
      unread: true,
      status: 0
    }
    const res = await getUserInfo(message.sender)
    if (path === '/contact/new-friends') applyFriend.unread = false
    store.commit('user/SET_APPLYFRIEND', { ...applyFriend, ...res.data }) // 存储消息
    return
  }
  if (message.action === '106') {
    // 同意加好友
    const res = await getUserInfo(message.sender)
    const reply = {
      id: res.data.id,
      action: '0',
      title: res.data.name,
      msgList: [],
      groups: [],
      motto: res.data.motto,
      badge: 0
    }
    const msgs = {
      msgType: 0,
      msg: '我通过了你的朋友验证请求，现在我们可以开始聊天了'
    }
    reply.msgList.push(msgs)
    store.dispatch('user/replyList', { reply }) // 存储消息
    const baseInfo = store.getters.baseInfo
    const friendList = baseInfo.friendList || []
    friendList.push(res.data)
    baseInfo.friendList = friendList
    store.commit('user/SET_BASEINFO', baseInfo)
    return
  }
  if (message.action === '107') {
    const baseInfo = store.getters.baseInfo
    let fri = baseInfo.friendList || []
    let both = baseInfo.bothList || []
    const contact = baseInfo.contactList || []
    const isFri = both.find(ele => {
      return ele.id == message.sender
    })
    if (isFri) {
      both = both.filter(ele => {
        return ele.id != message.sender
      })
      contact.push(isFri)
    } else {
      fri = fri.filter(ele => {
        return ele.id != message.sender
      })
      let replyList = store.getters.replyList
      replyList = replyList.filter(el => {
        // 根据id判断有没有存储对应的聊天记录
        return message.sender != el.id
      })
      // console.log(replyList);
      store.dispatch('user/replyList', { reply: replyList }) // 存储消息
    }
    baseInfo.friendList = fri
    baseInfo.bothList = both
    baseInfo.contactList = contact
    store.commit('user/SET_BASEINFO', baseInfo)
  }

  if (message.action === '109') {
    // 消息销毁 ---- 删除本地就行
    if( !reply ) return;
    let index = reply.msgList.findIndex(item=>item.id  == message.content);
    reply.msgList.splice(index, 1);
  }
  if (message.action === '110') {
    //  但聊清空聊天记录
    if(!reply) return;
    reply.msgList = [];
  }


  if (message.action === '300') {
    // 收到被添加到群
    let { data } = await getGroupInfo(message.sender)
    data = data.data;
    if (!data) return;
    let res = await getUserInfo(message.extra)
        res = res.data;
    if (!reply) {
      reply = {
        id: data.id,
        action: '300',
        title: '',
        msgList: [],
        groups: [],
        message:'',
        sender: message.sender,
        sourceId: message.sender,
        sourceType: 2,
        type: 'group',
        memberList: data.memberList,
        messageId:message.id,
        name: data.name,
        badge: 0,
        remove: false,
        timestamp: new Date().getTime(),
      }
    }
    const msgs = {
      msgType: 0,
      format:'0',
      msgType:'0',
      action: '300',
      msg: res.data.name + '邀请你加入群聊',
      content: res.data.name + '邀请你加入群聊'
    }
    reply.remove = false;
    reply.groups = data.memberList
    reply.msgList.push(msgs)
    replyList = utils.serachAndCreateReply(reply, replyList);
    store.commit("setReplyList", replyList);


    return
  }

  if (message.action === '301') {
    // 自己被移出群聊
    let resGroupInfo  = await getGroupInfo(message.sender)  // 这里sender 是groupId
    let groupList  = resGroupInfo?.data?.data?.memberList ? resGroupInfo?.data?.data?.memberList : reply.memberList;
   
    if (!groupList) return;   
    if (reply) {
      const msgs = {
        format: '0',
        msgType: '0',
        content: message.content,
        msg: message.content,
        tips:  '你已经被移出群聊',
        ...message
      }
      reply.msgList.push(msgs);
      reply.memberList = groupList; // reply 自身的群成员数组要更新啊
      // sender 是群的Id
      if (message.sender === store.state.currentChatId) {
        store.commit("setChatList", reply.msgList); // 删除本地
      }
      store.commit('replyList', replyList) // 存储消息
    }
    return
  }

  if (message.action === '302') {
    // 别人退群消息
    let quitInfo = await getUserInfo(message.content)
    quitInfo = quitInfo.data;
    let { data } = await getGroupInfo(message.sender)
    if (!data || !data.data) return
    data = data.data;

    if (!reply) {
      // 如果没有回话列表
      reply = {
        id: message.sender,
        action: '3',
        title: data.name,
        msgList: [],
        memberList: data.memberList,
        sourceId: message.sender,
        sourceType: 2,
        type: 2,
        badge: 0,
        remove: false,
        uid: data.uid,
        state: data.state,
        timestamp: new Date().getTime(),
      }
    }
    const msgs = {
      format:0,
      msgType: 0,
      action: '302',
      msg: `${quitInfo.data.name}退出群聊`,
      content:`${quitInfo.data.name}退出群聊`,
      tips: `${quitInfo.data.name}退出群聊`,
    }
    reply.msgList.push(msgs)
    replyList = utils.serachAndCreateReply(reply, replyList);
    store.commit("setReplyList", replyList);
   

    return
  }
  if (message.action === '303') {
     // 别人退群消息  解散群聊
    if (reply) {
      reply.removed = true; // 群组已经被解散, 唯一标志
      const msgs = {
        msgType: 0,
        format: '0',
        msg: `群组已被解散`,
        tips: `群组已被解散`,
        ...message,
      };
      reply?.msgList.push(msgs); 
      store.commit('replyList', replyList);
      deleteChatSession(reply.sourceId);
    }
    return false
  }
  if (message.action === '304') {
   // 修改群名称
    // const { data } = await getGroupInfo(message.sender)
    // if (!data) return  
    if (reply) {
      const msgs = {
        msgType: 0,
        msg: message.content,
        tips: '群名称被修改为'+ message.content,
        ...message
      }
      reply.name = message.content;
      reply?.msgList.push(msgs)
      store.commit('replyList', replyList)
    }
    return
  }
  if (message.action === '305') {
    // 修改群描述
    if (reply) {
      const msgs = {
        action: '305',
        extra: message.extra,
        format: message.format,
        id: message.id,
        msg:message.content,
        content: message.content,
        tips: '群描述被修改为:' + message.content,
        receiver: message.receiver,
        sender: message.sender,
        timestamp: message.timestamp,
        unread: true
      }
      reply.msgList.push(msgs);
      reply.notice = message.content;  // 修改群描述
      reply.message = message.content;
      reply.messageId =  message.id; // 更新最新的消息值
      reply.tips = '群描述被修改为:' + message.content;
      // 如果正好是当前聊天
      if (message.sender === store.state.currentChatId) {
        store.commit("setChatList", reply.msgList); // 删除本地
      }
      store.commit('replyList', replyList) // 存储消息
    }


    return
  }
  
  if (message.action === '306') {
    // 修改群头像
    if (reply) {
      bus.$emit("gsRefresh", reply.sourceId);
    }
    return
  }




  if (message.action === '308') {
    // 群组禁言
    const baseInfo = store.getters.baseInfo
    const groupList = baseInfo.groupList || []
    groupList.forEach((item, index) => {
      if (item.id == message.sender) {
        groupList[index].state = 1
      }
    })
    if (reply) {
      reply.state = 1
      store.dispatch('user/replyList', { reply }) // 存储消息
    }
    baseInfo.groupList = groupList
    store.commit('user/SET_BASEINFO', baseInfo)
    return false
  }
  if (message.action === '309') {
    // 群组解除禁言
    const baseInfo = store.getters.baseInfo
    const groupList = baseInfo.groupList || []
    groupList.forEach((item, index) => {
      if (item.id == message.sender) {
        groupList[index].state = 0
      }
    })
    if (reply) {
      reply.state = 0
      store.dispatch('user/replyList', { reply }) // 存储消息
    }
    baseInfo.groupList = groupList
    store.commit('user/SET_BASEINFO', baseInfo)
    return false
  }

  if (message.action === '311') {
    // 别人添加到群
    const inviteInfo =reply.memberList.find(item=>item.uid == message.extra);  // 邀请人的信息
    let resGroupInfo  = await getGroupInfo(message.sender)  // 这里sender 是groupId
    let groupList  = resGroupInfo?.data?.data?.memberList ? resGroupInfo?.data?.data?.memberList : reply.memberList;
  
    if (!groupList) return;
    const contentIds = message.content.split(',') // 被邀请的人的id
    
    if (reply) {
      let msg = [];
      contentIds?.forEach((ele, eleIndex) => {
        const res = groupList.find(item=> ele == item.uid);
        msg.push(res.name); 
      });
      const msgs = {
        format: '0',
        msgType: '0',
        content: message.content,
        msg: message.content,
        tips: inviteInfo.name + '邀请' + msg.join(',') + '加入群聊',
        ...message
      }
      reply.msgList.push(msgs)
      // sender 是群的Id
      if (message.sender === store.state.currentChatId) {
        store.commit("setChatList", reply.msgList); // 删除本地
      }
      store.commit('replyList', replyList) // 存储消息
    }


      
 
    return
  }

  if (message.action == '312') {
    // 群收到别人被移出（ 2 种传递方式， 自己删除的和接受到别人删除的）
    if (reply) { 
      let memberList = reply.memberList;
      let  removedIds = message.content?.split(','); // 要被移除的人的id
      let removedUserInfo = [];
      for(let i = 0; i< removedIds.length; i++){
        let index = memberList.findIndex(item=> item.uid == removedIds[i]);
        if(index > -1){
          memberList.splice(index, 1)
        }
        let res =  await getUserInfo(removedIds[i]);
        removedUserInfo.push(res.data.data);
      }
       // 给会话自己更新一下新的群消息 --- 实时更新一下群数据
      let resGroupInfo  = await getGroupInfo(message.sender)  // 这里sender 是groupId
      let data  = resGroupInfo.data.data;  
      reply.memberList = data?.memberList ? data?.memberList : reply.memberList;
    
      let tips = '';
      removedUserInfo.forEach(userInfo=>{
        tips += userInfo.name;
      })
      
      reply.msgList.push({
        action: "312",
        format: "0",
        msgtype: 0,
        content: message.content,
        msg: tips + "被移除了群聊",
        tips: tips + "被移除了群聊"
      });
      reply.messageId =  message.id;
      reply.message =  tips + "被移除了群聊";  // 实时更新一下
      store.commit('setReplyList', replyList) // 存储消息
    }

     

    return
  }
  
  if (message.action == '317') {
    // 群销毁
    if(reply){
       const msgList = reply.msgList.filter(
        msgItem => msgItem.id != message.content
       );
       reply.msgList = msgList;
        // 正好是当前的会话
        if (message.sender === store.state.currentChatId) {
          store.commit("setChatList", msgList); // 删除本地
        }
        store.commit('setReplyList', replyList);
    }
 


  }


  // if(message.action === '315'){
  //   // 接受到群公告   
  //   if (reply) {
  //     reply.newmsgcount += 1;  // 新消息加一
  //     const msg = {
  //       action: '315',
  //       extra: message.extra,
  //       format: message.format,  // "6"
  //       id: message.id,  // 群公告本身的id 
  //       title:"群公告",
  //       msg: '群公告<br/>' + message.content,
  //       content: message.content,
  //       receiver: message.receiver,
  //       sender: message.sender,   // 群会话的id 
  //       timestamp: message.timestamp,
  //       unread: true,
  //       issend:false,
  //     }
  //     reply.msgList.push(msg); // 插入到对应的会话列表中去
  //     replyList = utils.calcReplyListSort(replyList,  reply)
  //     store.commit('replyList', replyList) // 存储消息
  //   }
  //   return

  // }
 
  // const replyMsgs = replyMsg(reply, message)
  // store.dispatch('setReplyList', { reply: replyMsgs }) 
}
